package com.chenjl.exchange;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chenjl.transport.HookChannelHandler;
import com.chenjl.transport.support.NettyServer;

import io.netty.channel.Channel;
/**
 * 模拟Exchange服务器
 * 2016-9-2 14:17:28
 * @author chenjinlong
 */
public class ExchangeServer {
	private static final Logger logger = LoggerFactory.getLogger(ExchangeServer.class);
	
	public static void main(String[] args) {
		HookChannelHandler hookChannelHandler = new HookChannelHandler() {
			@Override
			public void channelRead(Channel channel,Object msg) throws Exception {
				logger.info("receive message from client : {} , channel.remoteAddress : {}",msg,channel.remoteAddress());
				
				if(msg.getClass() == Request.class) {
					Request request = (Request) msg;
					
					Random random = new Random();
					int seed = random.nextInt(3)+1;
					logger.info("sleep seed : {}",seed);
					Thread.sleep(seed*1000);
					
					Response response = new Response(request.getId());
					response.setData("response :"+request.getData()+" , seed : "+seed);
					channel.writeAndFlush(response);
				}
				else {
					logger.error("client receive message from server : {}, can not handle ",msg);
				}
			}
		};
		NettyServer server = new NettyServer(hookChannelHandler);
		server.open();
		
		try {
			Thread.sleep(20*1000);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		server.close();
	}
}